#include "texel.h"

#include <string>
#include "xmlhelpers.h"

Texel::Texel () {
	state = 0;
}

Texel::Texel (rapidxml::xml_node<> * node) throw(Error) {
	std::string type;
	XMLGetValue(type, node, "type");
	if (type == "static") {
		GetStaticParams(node);
	} else if (type == "bomb") {
		GetStaticParams(node);
		GetBombParams(node);
		EnableTicks();
	}
}

Texel::~Texel () {
}

void Texel::GetStaticParams (rapidxml::xml_node<> * node) throw(Error) {
	XMLGetValue(state, node, "defaultState");
	XMLGetValue(statesCount, node, "statesCount");
	XMLGetValue(durability, node, "durability");
	XMLGetValue(maxDurability, node, "durability");
	XMLGetValue(destroyable, node, "isDestroyable");
	XMLGetValue(empty, node, "isEmpty");
	XMLGetValue(gatherable, node, "isGatherable");
	XMLGetValue(detonateable, node, "isDetonateable");
	XMLGetValue(tickable, node, "isTickable");
	std::string texture_file;
	XMLGetValue(texture_file, node, "texture");
	texture.Load(texture_file);
	bombExploding = false;
}

void Texel::GetBombParams (rapidxml::xml_node<>* node) throw(Error) {
	rapidxml::xml_node<>* bomb_node = XMLGetNode(node, "explosion");
	XMLGetValue(bombDamage, bomb_node, "damage");
	XMLGetValue(bombRadius, bomb_node, "radius");
	XMLGetValue(bombDelay, bomb_node, "delay");
}

void Texel::EnableTicks () {
	bombTime = SDL_GetTicks();
	tickable = true;
}

void Texel::Detonate () {
}

bool Texel::IsEmpty () {
	return empty;
}

bool Texel::IsDestroyable () {
	return destroyable;
}

int Texel::GetState () {
	return state;
}

void Texel::Demolish () {
		(*this) = ((*table)['a']);
}

void Texel::Destroy () {
	if (destroyable) {
		Demolish();
	}
}

void Texel::Dig (int damage) {
	durability = (durability > damage) ? durability - damage : 0;
	if (durability == 0) {
		Destroy();
	}
	state = statesCount - ((statesCount * durability / maxDurability) % statesCount) - 1;
}

void Texel::Explode (int damage) {
	Dig(damage);
	if (detonateable) {
		Detonate();
	}
}

void Texel::Draw(SDL_Surface * screen, int x, int y) {
	texture.Draw(screen, x, y, state);
}

void Texel::HandleTick(unsigned time) {
	state = ((statesCount * (time - bombTime) / bombDelay) % statesCount);
	if (time > bombTime + bombDelay) {
		bombExploding = true;
	}
}
